package Day2025_03_10;

import java.util.*;

public class LeetCode207 {
    public boolean canFinish(int numCourses, int[][] p) {
        int m = p.length;
        int[] in = new int[numCourses];
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < m; i++) {
            int a = p[i][0], b = p[i][1];
            if (!map.containsKey(b)) {
                map.put(b, new ArrayList<>());
            }
            map.get(b).add(a);
            in[a]++;
        }
        Queue<Integer> q = new LinkedList<>();
        for (int i =0 ; i < numCourses; i++) {
            if (in[i] == 0) q.add(i);
        }

        while (!q.isEmpty()) {
            int t = q.poll();
            for (int x : map.getOrDefault(t, new ArrayList<>())) {
                in[x]--;
                if (in[x] == 0) q.add(x);
            }
        }

        for (int i = 0; i < numCourses; i++) {
            if (in[i] != 0) return false;
        }
        return true;
    }
}
